package cn.service.impl;

import cn.mapper.HealthUserMapper;
import cn.pojo.HealthUser;
import cn.service.HealthUserService;
import cn.utils.FileUtils;
import cn.utils.ImageUtils;
import cn.utils.LoggerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HealthUserServiceImpl implements HealthUserService {

    @Autowired
    private HealthUserMapper userMapper;

    @Override
    public Map<String, Object> saveUser(HealthUser user) {
        Map<String, Object> map = new HashMap<>();
        boolean ok = false;
        try {
            ok = userMapper.saveUser(user) == 1;
        } catch (Exception e) {
            ok = false;
            e.printStackTrace();
        }
        map.put("msg", ok);
        LoggerUtils.info("添加用户：" + ok);
        return map;
    }

    @Override
    public Map<String, Object> selectUser(String openid) {
        Map<String, Object> map = new HashMap<>();
        boolean ok = false;
        List<HealthUser> healthUsers = userMapper.selectUser(openid);
        if (healthUsers.size() == 1) {
            ok = true;
            map.put("data", healthUsers.get(0));
            LoggerUtils.info("用户信息" + healthUsers);
        } else {
            ok = false;
        }
        map.put("msg", ok);
        return map;
    }

    @Override
    public Map<String, Object> updateUser(HealthUser user) {
        Map<String, Object> map = new HashMap<>();
        boolean ok = false;
        try {
            ok = userMapper.updateUser(user) == 1;
        } catch (Exception e) {
            ok = false;
            e.printStackTrace();
        }
        map.put("msg", ok);
        return null;
    }

    @Override
    public Map<String, Object> uploadIdCard(MultipartFile file, String openId, boolean isFront) {
        // 将图片存入本地并生成本地链接跟网络链接
        Map<String, Object> imgUrl = FileUtils.uploadtest(file, openId);

        // 用户信息对象
        HealthUser user = new HealthUser();

        user.setUserIdCardPath((String) imgUrl.get("cloudPath"));
        user.setUserOpenId(openId);

        Map<String, Object> updateRes = this.updateUser(user);

        return ImageUtils.getIdCardInfo((String) imgUrl.get("localPath"), isFront, openId);
    }
}
